package com.ktgj.train.controller;

import cn.hutool.core.codec.Base64Decoder;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.ktgj.common.core.constant.BusinessTypeConstants;
import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.common.core.constant.FlightOrderChangeConstants;
import com.ktgj.common.core.constant.FlightOrderConstants;
import com.ktgj.common.core.enums.TrainOrderEnum;
import com.ktgj.common.core.utils.xml.XElement;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.BillPayment;
import com.ktgj.customer.api.domain.PaymentCallbackVo;
import com.ktgj.pay.api.RemotePayService;
import com.ktgj.pay.api.domain.AlipayConfigApi;
import com.ktgj.train.common.TrainTickets;
import com.ktgj.train.domain.InterfaceEntity.TrConfirmChangeRequest;
import com.ktgj.train.domain.InterfaceEntity.TrConfirmChangeResponse;
import com.ktgj.train.domain.InterfaceEntity.TrOutTicketRequest;
import com.ktgj.train.domain.InterfaceEntity.TrOutTicketResponse;
import com.ktgj.train.domain.TrainOrder;
import com.ktgj.train.domain.TrainOrderOperation;
import com.ktgj.train.domain.TrainOrderRefundrecord;
import com.ktgj.train.domain.TrainOrderitem;
import com.ktgj.train.domain.vo.PhoneSoundCallback;
import com.ktgj.train.mapper.TrainOrderOperationMapper;
import com.ktgj.train.service.ITrainOrderRefundrecordService;
import com.ktgj.train.service.ITrainOrderService;
import com.ktgj.train.service.ITrainOrderitemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.*;

@ControllerAdvice
@RestController
@RequestMapping("/callback")
public class CallbackController {
    @Autowired
    private ITrainOrderService trainOrderService;
    @Autowired
    private ITrainOrderitemService trainOrderitemService;
    @Autowired
    private TrainTickets trainTickets;
    @Autowired
    private RemotePayService payService;
    @Autowired
    private ITrainOrderRefundrecordService trainOrderRefundrecordService;
    @Autowired
    private RemoteCustomerService remoteCustomerService;
    @Autowired
    private TrainOrderOperationMapper trainOrderOperationMapper;

    //bankPayCallback

    /**
     * 微信小程序支付回调
     * @param resultMap
     * @param resultMap
     */
    @RequestMapping("/wechatPayCallback")
    public void wechatPayCallback(@RequestBody Map<String, String> resultMap) {
        boolean result = payService.isPaySuccessful(resultMap);
        String returnCode = resultMap.put("return_code", resultMap.get("return_code"));
        String resultCode = resultMap.put("result_code", resultMap.get("result_code"));
        String outTradeNo = resultMap.put("out_trade_no", resultMap.get("out_trade_no"));
        String transaction_id = resultMap.put("transaction_id", resultMap.get("transaction_id"));
        if (result) {
            if (returnCode.equals("SUCCESS") && resultCode.equals("SUCCESS")) {//交易成功
                if (outTradeNo != null) {//商户订单号
                    TrainOrder trainOrder = trainOrderService.selectTrainOrderByOrderId(outTradeNo);
                    TrainOrderOperation orderOperation = new TrainOrderOperation();
                    orderOperation.setOperationname("支付成功");
                    orderOperation.setOrderid(trainOrder.getOrderid());
                    orderOperation.setOpemployeeid(1L);
                    orderOperation.setOpemployeename("系统服务");
                    orderOperation.setCreateTime(new Date());
                    trainOrderOperationMapper.insertTrainOrderOperation(orderOperation);
                    TrOutTicketRequest ticketRequest = new TrOutTicketRequest();
                    ticketRequest.transactionid = trainOrder.getOrderpartnernumber();
                    ticketRequest.orderid = trainOrder.getMerchantOrderId();
                    if (!trainOrder.getPaymentorderstatus().equals(CustomerConstants.payd.getValue()) && !trainOrder.getStatus().equals(FlightOrderConstants.ticketing.getValue())) {
                        trainOrder.setPaymentorderstatus(CustomerConstants.payd.getValue());
                        trainOrder.setStatus(CustomerConstants.payd.getValue());
                        trainOrder.setPayType(BusinessTypeConstants.Wechat.getValue());
                        trainOrder.setBillNo(transaction_id);
                        trainOrderService.updateTrainOrder(trainOrder);

                        TrainOrderitem orderitem = new TrainOrderitem();
                        orderitem.setOrderid(trainOrder.getOrderid());
                        orderitem.setStatus(CustomerConstants.payd.getValue());
                        trainOrderitemService.updateByOrderId(orderitem);

                        TrOutTicketResponse response = trainTickets.outTicket(ticketRequest);
                        if (response.success) {
                            trainOrder.setStatus(FlightOrderConstants.ticketing.getValue());
                            trainOrderService.updateTrainOrder(trainOrder);
                        }
                        System.out.println("确认出票：" + response.toString());
                    }
                }
            } else {
                if (outTradeNo != null) {
                    TrainOrder trainOrder = trainOrderService.selectTrainOrderByOrderId(outTradeNo);
                    TrainOrderOperation orderOperation = new TrainOrderOperation();
                    orderOperation.setOperationname("支付失败");
                    orderOperation.setOrderid(trainOrder.getOrderid());
                    orderOperation.setOpemployeeid(1L);
                    orderOperation.setOpemployeename("系统服务");
                    orderOperation.setCreateTime(new Date());
                    trainOrderOperationMapper.insertTrainOrderOperation(orderOperation);
                    TrOutTicketRequest ticketRequest = new TrOutTicketRequest();
                    ticketRequest.transactionid = trainOrder.getOrderpartnernumber();
                    ticketRequest.orderid = trainOrder.getMerchantOrderId();
                    if (!trainOrder.getPaymentorderstatus().equals(CustomerConstants.failPay.getValue()) && !trainOrder.getStatus().equals(FlightOrderConstants.failPay.getValue())) {
                        trainOrder.setPaymentorderstatus(CustomerConstants.failPay.getValue());
                        trainOrder.setStatus(CustomerConstants.failPay.getValue());
                        trainOrder.setPayType(BusinessTypeConstants.Wechat.getValue());
                        trainOrder.setBillNo(transaction_id);
                        trainOrderService.updateTrainOrder(trainOrder);

                        TrainOrderitem orderitem = new TrainOrderitem();
                        orderitem.setOrderid(trainOrder.getOrderid());
                        orderitem.setStatus(CustomerConstants.failPay.getValue());
                        trainOrderitemService.updateByOrderId(orderitem);
                    }
                }
            }
        }
    }

    /**
     * 改签微信小程序支付
     * @param resultMap
     */
    @RequestMapping("/changeWechatPayCallback")
    public void changeWechatPayCallback(@RequestBody Map<String, String> resultMap) {
        boolean result = payService.isPaySuccessful(resultMap);
        String returnCode = resultMap.put("return_code", resultMap.get("return_code"));
        String resultCode = resultMap.put("result_code", resultMap.get("result_code"));
        String outTradeNo = resultMap.put("out_trade_no", resultMap.get("out_trade_no"));
        String transaction_id = resultMap.put("transaction_id", resultMap.get("transaction_id"));
        if (result) {
            TrainOrder trainOrder = trainOrderService.selectTrainOrderById(Long.valueOf(outTradeNo));
            List<TrainOrderRefundrecord> trainOrderRefundrecords = trainOrderRefundrecordService.queryTrainOrderRefundrecordList(Long.valueOf(outTradeNo), FlightOrderChangeConstants.change.getValue());
            if (returnCode.equals("SUCCESS") && resultCode.equals("SUCCESS")) {
                TrainOrderOperation orderOperation = new TrainOrderOperation();
                orderOperation.setOperationname("支付成功");
                orderOperation.setOrderid(trainOrder.getOrderid());
                orderOperation.setOpemployeeid(1L);
                orderOperation.setOpemployeename("系统服务");
                orderOperation.setCreateTime(new Date());
                trainOrderOperationMapper.insertTrainOrderOperation(orderOperation);
                //交易成功
                if (outTradeNo != null) {//商户订单号
                    TrConfirmChangeRequest changeRequest = new TrConfirmChangeRequest();
                    changeRequest.isasync = "Y";
                    changeRequest.transactionid = trainOrder.getOrderpartnernumber();
                    changeRequest.orderid = trainOrderRefundrecords.get(0).getMerchantOrderId();
                    changeRequest.reqtoken = trainOrderRefundrecords.get(0).getReqToken();
                    boolean match = trainOrderRefundrecords.stream().allMatch(item -> item.getPaymentOrderStatus() != null && !item.getPaymentOrderStatus().equals(FlightOrderConstants.payd.toString()) &&
                            item.getOrderStatus() != null && !item.getOrderStatus().equals(FlightOrderConstants.ticketing.getValue()));
                    if (!match) {
                        TrConfirmChangeResponse response = trainTickets.confirmChange(changeRequest);
                        if (response.success) {
                            trainOrder.setStatus(TrainOrderEnum.changeTicketSuccess.getValue());
                            trainOrderRefundrecords.forEach(item -> {
                                item.setPaymentOrderStatus(FlightOrderConstants.payd.toString());
                                item.setOrderStatus(FlightOrderConstants.ticketing.getValue());
                                item.setBillNo(transaction_id);
                                item.setPayType(BusinessTypeConstants.Wechat.getValue());
                                item.setChangeType("change");
                                trainOrderRefundrecordService.updateByOrderItemId(item);
                            });
                            trainOrderService.updateTrainOrder(trainOrder);
                        } else {
                            trainOrder.setStatus(TrainOrderEnum.changeTicketFail.getValue());
                            trainOrderService.updateTrainOrder(trainOrder);
                            trainOrderRefundrecords.forEach(item -> {
                                item.setPaymentOrderStatus(FlightOrderConstants.failPay.toString());
                                item.setOrderStatus(FlightOrderConstants.failPay.toString());
                                item.setPayType(BusinessTypeConstants.Wechat.getValue());
                                item.setChangeType("change");
                                trainOrderRefundrecordService.updateByOrderItemId(item);
                            });
                        }
                    }
                }
            } else {
                trainOrder.setStatus(TrainOrderEnum.changeTicketFail.getValue());
                trainOrderService.updateTrainOrder(trainOrder);
                trainOrderRefundrecords.forEach(item -> {
                    item.setPaymentOrderStatus(FlightOrderConstants.failPay.toString());
                    item.setOrderStatus(FlightOrderConstants.failPay.toString());
                    item.setPayType(BusinessTypeConstants.Wechat.getValue());
                    item.setChangeType("change");
                    trainOrderRefundrecordService.updateByOrderItemId(item);
                });
                TrainOrderOperation orderOperation = new TrainOrderOperation();
                orderOperation.setOperationname("支付失败");
                orderOperation.setOrderid(trainOrder.getOrderid());
                orderOperation.setOpemployeeid(1L);
                orderOperation.setOpemployeename("系统服务");
                orderOperation.setCreateTime(new Date());
                trainOrderOperationMapper.insertTrainOrderOperation(orderOperation);
            }
        }
    }

    /**
     * 银联二维码回调
     * */
    @RequestMapping("/trainVoicePayCallback")
    public void trainVoicePayCallback(HttpServletResponse response, HttpServletRequest request){
        PaymentCallbackVo paymentCallbackVo = new PaymentCallbackVo();
        String parameter = request.getParameter("billPayment");
        BillPayment parseObject = JSONObject.parseObject(parameter, BillPayment.class);
        paymentCallbackVo.setBillPayment(parseObject);
        paymentCallbackVo.setMid(request.getParameter("mid"));//商户号
        paymentCallbackVo.setTid(request.getParameter("tid"));//终端号
        paymentCallbackVo.setInstMid(request.getParameter("instMid"));//业务类型
        paymentCallbackVo.setBillNo(request.getParameter("billNo"));//账单号
        paymentCallbackVo.setBillQRCode(request.getParameter("billQRCode"));//账单二维码
        paymentCallbackVo.setBillStatus(request.getParameter("billStatus"));//账单状态
        paymentCallbackVo.setBillDesc(request.getParameter("billDesc"));//账单描述
        paymentCallbackVo.setMemberId(request.getParameter("memberId"));//会员号
        paymentCallbackVo.setCounterNo(request.getParameter("counterNo"));//桌号、柜台号、房间号
        paymentCallbackVo.setMerName(request.getParameter("merName"));//商户名称
        paymentCallbackVo.setMemo(request.getParameter("memo"));//付款附言
        paymentCallbackVo.setNotifyId(request.getParameter("notifyId"));//支付通知ID
        paymentCallbackVo.setSecureStatus(request.getParameter("secureStatus"));//担保状态
        paymentCallbackVo.setCompleteAmount(request.getParameter("completeAmount"));//担保完成金额（分）
        paymentCallbackVo.setBillDate(request.getParameter("billDate"));//订单时间，格式yyyy-MM-dd
        paymentCallbackVo.setCreateTime(request.getParameter("createTime"));//账单创建时间，格式yyyy-MM-dd HH:mm:ss
        paymentCallbackVo.setSign(request.getParameter("sign"));//签名
        paymentCallbackVo.setExtraBuyerInfo(request.getParameter("extraBuyerInfo"));//用户额外信息

        TrainOrder trainOrder = trainOrderService.selectTrainOrderByOrderId(paymentCallbackVo.getBillNo().substring(4));
        if (paymentCallbackVo.getBillStatus().equals("PAID")) {
            TrainOrderOperation orderOperation = new TrainOrderOperation();
            orderOperation.setOperationname("支付成功");
            orderOperation.setOrderid(trainOrder.getOrderid());
            orderOperation.setOpemployeeid(1L);
            orderOperation.setOpemployeename("系统服务");
            orderOperation.setCreateTime(new Date());
            trainOrderOperationMapper.insertTrainOrderOperation(orderOperation);
            if (!trainOrder.getPaymentorderstatus().equals(CustomerConstants.payd.getValue()) && !trainOrder.getStatus().equals(FlightOrderConstants.ticketing.getValue())) {
                trainOrder.setPaymentorderstatus(FlightOrderConstants.payd.toString());
                trainOrder.setStatus(FlightOrderConstants.payd.toString());
                trainOrder.setPayType(BusinessTypeConstants.UnionPayQRCode.getValue());
                trainOrder.setBillNo(paymentCallbackVo.getBillNo());
                trainOrderService.updateTrainOrder(trainOrder);

                TrOutTicketRequest ticketRequest = new TrOutTicketRequest();
                ticketRequest.transactionid = trainOrder.getOrderpartnernumber();
                ticketRequest.orderid = trainOrder.getMerchantOrderId();

                TrOutTicketResponse ticketResponse = trainTickets.outTicket(ticketRequest);
                if (ticketResponse.success) {
                    TrainOrder train = new TrainOrder();
                    train.setOrderid(trainOrder.getOrderid());
                    train.setStatus(FlightOrderConstants.ticketing.getValue());
                    trainOrderService.updateTrainOrder(train);

                    TrainOrderitem orderitem = new TrainOrderitem();
                    orderitem.setOrderid(trainOrder.getOrderid());
                    orderitem.setStatus(String.valueOf(FlightOrderConstants.ticketing.getValue()));
                    trainOrderitemService.updateByOrderId(orderitem);
                } else {
                    TrainOrder train = new TrainOrder();
                    train.setOrderid(trainOrder.getOrderid());
                    train.setStatus(FlightOrderConstants.ticketingFail.getValue());
                    trainOrderService.updateTrainOrder(train);

                    TrainOrderitem orderitem = new TrainOrderitem();
                    orderitem.setOrderid(trainOrder.getOrderid());
                    orderitem.setStatus(String.valueOf(FlightOrderConstants.ticketingFail.getValue()));
                    trainOrderitemService.updateByOrderId(orderitem);
                }
            }
        } else {
            trainOrder.setPaymentorderstatus(FlightOrderConstants.failPay.toString());
            trainOrder.setStatus(FlightOrderConstants.failPay.toString());
            trainOrderService.updateTrainOrder(trainOrder);
            TrainOrderOperation orderOperation = new TrainOrderOperation();
            orderOperation.setOperationname("支付失败");
            orderOperation.setOrderid(trainOrder.getOrderid());
            orderOperation.setOpemployeeid(1L);
            orderOperation.setOpemployeename("系统服务");
            orderOperation.setCreateTime(new Date());
            trainOrderOperationMapper.insertTrainOrderOperation(orderOperation);
        }

        PrintWriter printWriter;
        response.setCharacterEncoding("UTF-8");
        try {
            printWriter = response.getWriter();
            printWriter.write("SUCCESS");
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 改签银联二维码回调
     * */
    @RequestMapping("/trainChangeVoicePayCallback")
    public void trainChangeVoicePayCallback(HttpServletResponse response, HttpServletRequest request){
        PaymentCallbackVo paymentCallbackVo = new PaymentCallbackVo();
        String parameter = request.getParameter("billPayment");
        BillPayment parseObject = JSONObject.parseObject(parameter, BillPayment.class);
        paymentCallbackVo.setBillPayment(parseObject);
        paymentCallbackVo.setMid(request.getParameter("mid"));//商户号
        paymentCallbackVo.setTid(request.getParameter("tid"));//终端号
        paymentCallbackVo.setInstMid(request.getParameter("instMid"));//业务类型
        paymentCallbackVo.setBillNo(request.getParameter("billNo"));//账单号
        paymentCallbackVo.setBillQRCode(request.getParameter("billQRCode"));//账单二维码
        paymentCallbackVo.setBillStatus(request.getParameter("billStatus"));//账单状态
        paymentCallbackVo.setBillDesc(request.getParameter("billDesc"));//账单描述
        paymentCallbackVo.setMemberId(request.getParameter("memberId"));//会员号
        paymentCallbackVo.setCounterNo(request.getParameter("counterNo"));//桌号、柜台号、房间号
        paymentCallbackVo.setMerName(request.getParameter("merName"));//商户名称
        paymentCallbackVo.setMemo(request.getParameter("memo"));//付款附言
        paymentCallbackVo.setNotifyId(request.getParameter("notifyId"));//支付通知ID
        paymentCallbackVo.setSecureStatus(request.getParameter("secureStatus"));//担保状态
        paymentCallbackVo.setCompleteAmount(request.getParameter("completeAmount"));//担保完成金额（分）
        paymentCallbackVo.setBillDate(request.getParameter("billDate"));//订单时间，格式yyyy-MM-dd
        paymentCallbackVo.setCreateTime(request.getParameter("createTime"));//账单创建时间，格式yyyy-MM-dd HH:mm:ss
        paymentCallbackVo.setSign(request.getParameter("sign"));//签名
        paymentCallbackVo.setExtraBuyerInfo(request.getParameter("extraBuyerInfo"));//用户额外信息

        TrainOrder trainOrder = trainOrderService.selectTrainOrderById(Long.valueOf(paymentCallbackVo.getBillNo().substring(4)));
        List<TrainOrderRefundrecord> trainOrderRefundrecords = trainOrderRefundrecordService.queryTrainOrderRefundrecordList(Long.valueOf(paymentCallbackVo.getBillNo().substring(4)), FlightOrderChangeConstants.change.getValue());
        TrConfirmChangeRequest changeRequest = new TrConfirmChangeRequest();
        changeRequest.isasync = "Y";
        changeRequest.transactionid = trainOrder.getOrderpartnernumber();
        changeRequest.orderid = trainOrderRefundrecords.get(0).getMerchantOrderId();
        changeRequest.reqtoken = trainOrderRefundrecords.get(0).getReqToken();
        if (paymentCallbackVo.getBillStatus().equals("PAID")) {
            TrainOrderOperation orderOperation = new TrainOrderOperation();
            orderOperation.setOperationname("支付成功");
            orderOperation.setOrderid(trainOrder.getOrderid());
            orderOperation.setOpemployeeid(1L);
            orderOperation.setOpemployeename("系统服务");
            orderOperation.setCreateTime(new Date());
            trainOrderOperationMapper.insertTrainOrderOperation(orderOperation);
            boolean match = trainOrderRefundrecords.stream().allMatch(item -> item.getPaymentOrderStatus() != null && !item.getPaymentOrderStatus().equals(FlightOrderConstants.payd.toString()) &&
                    item.getOrderStatus() != null && !item.getOrderStatus().equals(FlightOrderConstants.ticketing.getValue()));
            if (!match) {
                TrConfirmChangeResponse change = trainTickets.confirmChange(changeRequest);
                if (change.success) {
                    trainOrder.setStatus(TrainOrderEnum.changeTicketSuccess.getValue());
                    trainOrderRefundrecords.forEach(item -> {
                        item.setPaymentOrderStatus(FlightOrderConstants.payd.toString());
                        item.setOrderStatus(FlightOrderConstants.ticketing.getValue());
                        item.setBillNo(paymentCallbackVo.getBillNo());
                        item.setPayType(BusinessTypeConstants.UnionPayQRCode.getValue());
                        item.setChangeType("change");
                        trainOrderRefundrecordService.updateByOrderItemId(item);
                    });
                    trainOrderService.updateTrainOrder(trainOrder);
                } else {
                    trainOrder.setStatus(TrainOrderEnum.changeTicketFail.getValue());
                    trainOrderService.updateTrainOrder(trainOrder);
                    trainOrderRefundrecords.forEach(item -> {
                        item.setPaymentOrderStatus(FlightOrderConstants.failPay.toString());
                        item.setOrderStatus(FlightOrderConstants.failPay.toString());
                        item.setPayType(BusinessTypeConstants.UnionPayQRCode.getValue());
                        item.setChangeType("change");
                        trainOrderRefundrecordService.updateByOrderItemId(item);
                    });
                }
            }
        } else {
            trainOrder.setStatus(TrainOrderEnum.changeTicketFail.getValue());
            trainOrderService.updateTrainOrder(trainOrder);
            trainOrderRefundrecords.forEach(item -> {
                item.setPaymentOrderStatus(FlightOrderConstants.failPay.toString());
                item.setOrderStatus(FlightOrderConstants.failPay.toString());
                item.setPayType(BusinessTypeConstants.UnionPayQRCode.getValue());
                item.setChangeType("change");
                trainOrderRefundrecordService.updateByOrderItemId(item);
            });
            TrainOrderOperation orderOperation = new TrainOrderOperation();
            orderOperation.setOperationname("支付失败");
            orderOperation.setOrderid(trainOrder.getOrderid());
            orderOperation.setOpemployeeid(1L);
            orderOperation.setOpemployeename("系统服务");
            orderOperation.setCreateTime(new Date());
            trainOrderOperationMapper.insertTrainOrderOperation(orderOperation);
        }

        PrintWriter printWriter;
        response.setCharacterEncoding("UTF-8");
        try {
            printWriter = response.getWriter();
            printWriter.write("SUCCESS");
            printWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 支付宝回调
     * @param request
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/aliPayCallback")
    public void aliPayCallback(HttpServletRequest request) throws UnsupportedEncodingException {
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        //log.info("支付宝验签:{}", jsonString4JavaPOJO);

        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        String out_trade_no = request.getParameter("out_trade_no");            // 商户订单号
        String trade_no = request.getParameter("trade_no");            // 流水号
        String tradeStatus = request.getParameter("trade_status");
        String total_amount = request.getParameter("total_amount");  //订单金额

        //签名验证(对支付宝返回的数据验证，确定是支付宝返回的)
        boolean signVerified = false;
        try {
            //3.1调用SDK验证签名
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfigApi.ALIPAY_PUBLIC_KEY, AlipayConfigApi.CHARSET, AlipayConfigApi.SIGN_TYPE);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //4.对验签进行处理
        if (signVerified) {    //验签通过
            if (tradeStatus.equals("TRADE_SUCCESS")) {    //只处理支付成功的订单: 修改交易表状态,支付成功
                TrainOrder trainOrder = trainOrderService.selectTrainOrderByOrderId(out_trade_no);
                TrOutTicketRequest ticketRequest = new TrOutTicketRequest();
                ticketRequest.transactionid = trainOrder.getOrderpartnernumber();
                ticketRequest.orderid = trainOrder.getMerchantOrderId();

                TrainOrder order = new TrainOrder();
                order.setOrderid(trainOrder.getOrderid());
                order.setPaymentorderstatus(CustomerConstants.payd.getValue());
                order.setStatus(CustomerConstants.payd.getValue());
                trainOrderService.updateTrainOrder(order);

                TrainOrderitem orderitem = new TrainOrderitem();
                orderitem.setOrderid(trainOrder.getOrderid());
                orderitem.setStatus(CustomerConstants.payd.getValue());
                trainOrderitemService.updateByOrderId(orderitem);

                /*TrOutTicketResponse response = trainTickets.outTicket(ticketRequest);
                if (response.success) {
                    TrainOrder train = new TrainOrder();
                    train.setOrderid(trainOrder.getOrderid());
                    train.setStatus(FlightOrderConstants.ticketing.getValue());
                    trainOrderService.updateTrainOrder(train);
                }
                System.out.println("确认出票：" + response.toString());*/
            }
        }
    }

    /**
     * 语音支付回调
     * */
    @RequestMapping("/voiceCallback")
    public void voiceCallback(HttpServletResponse response, HttpServletRequest request) {
        PhoneSoundCallback phoneSoundCallback = new PhoneSoundCallback();
        try
        {
            request.setCharacterEncoding("UTF-8");
//            response_xml=String(Base64Decode(UrlDecode(request.getParameter(response_text),UTF-8)),UTF-8)
            String response_xml = Base64Decoder.decodeStr(request.getParameter("response_text"));
            XElement root = XElement.loadXml(response_xml);
            phoneSoundCallback.setAccountType(root.element("AccountType").getValue());
            phoneSoundCallback.setAcqSsn(root.element("AcqSsn").getValue());
            phoneSoundCallback.setAmount(root.element("Amount").getValue());
            phoneSoundCallback.setAccountNo(root.element("AccountNo").getValue());
            phoneSoundCallback.setAsynAddress(root.element("AsynAddress").getValue());
            phoneSoundCallback.setCurrency(root.element("Currency").getValue());
            phoneSoundCallback.setDescription(root.element("Description").getValue());
            phoneSoundCallback.setMAC(root.element("MAC").getValue());
            phoneSoundCallback.setMerchantNo(root.element("MerchantNo").getValue());
            phoneSoundCallback.setMerchantOrderNo(root.element("MerchantOrderNo").getValue());
            phoneSoundCallback.setMethod(root.element("Method").getValue());
            phoneSoundCallback.setOrderNo(root.element("OrderNo").getValue());
            phoneSoundCallback.setOrderState(root.element("OrderState").getValue());
            phoneSoundCallback.setOrderType(root.element("OrderType").getValue());
            phoneSoundCallback.setProcCode(root.element("ProcCode").getValue());
            phoneSoundCallback.setProcessCode(root.element("ProcessCode").getValue());
            phoneSoundCallback.setRemark(root.element("Remark").getValue());
            phoneSoundCallback.setRespCode(root.element("RespCode").getValue());
            phoneSoundCallback.setSettleDate(root.element("SettleDate").getValue());
            phoneSoundCallback.setTerminalNo(root.element("TerminalNo").getValue());
            phoneSoundCallback.setTsNo(root.element("TsNo").getValue());
            phoneSoundCallback.setUpsNo(root.element("UpsNo").getValue());
            phoneSoundCallback.setUserPayedTime(root.element("UserPayedTime").getValue());
            phoneSoundCallback.setVersion(root.element("Version").getValue());
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        TrainOrder trainOrder = trainOrderService.selectTrainOrderByOrderId(phoneSoundCallback.getOrderNo());
        if (phoneSoundCallback.getRespCode().equals("0000")){//交易成功
            TrainOrderOperation orderOperation = new TrainOrderOperation();
            orderOperation.setOperationname("支付成功");
            orderOperation.setOrderid(trainOrder.getOrderid());
            orderOperation.setOpemployeeid(1L);
            orderOperation.setOpemployeename("系统服务");
            orderOperation.setCreateTime(new Date());
            trainOrderOperationMapper.insertTrainOrderOperation(orderOperation);
            if (phoneSoundCallback.getMerchantOrderNo() != null){
                trainOrder.setPaymentorderstatus(FlightOrderConstants.payd.toString());
                trainOrder.setStatus(FlightOrderConstants.payd.toString());
                trainOrderService.updateTrainOrder(trainOrder);

                TrOutTicketRequest ticketRequest = new TrOutTicketRequest();
                ticketRequest.transactionid = trainOrder.getOrderpartnernumber();
                ticketRequest.orderid = trainOrder.getMerchantOrderId();

                TrOutTicketResponse ticketResponse = trainTickets.outTicket(ticketRequest);
                if (ticketResponse.success) {
                    TrainOrder train = new TrainOrder();
                    train.setOrderid(trainOrder.getOrderid());
                    train.setStatus(FlightOrderConstants.ticketing.getValue());
                    trainOrderService.updateTrainOrder(train);
                }
            }
        }
        else {
            if (phoneSoundCallback.getMerchantOrderNo() != null){
                trainOrder.setPaymentorderstatus(FlightOrderConstants.failPay.toString());
                trainOrder.setStatus(FlightOrderConstants.failPay.toString());
                trainOrderService.updateTrainOrder(trainOrder);
            }
            TrainOrderOperation orderOperation = new TrainOrderOperation();
            orderOperation.setOperationname("支付失败");
            orderOperation.setOrderid(trainOrder.getOrderid());
            orderOperation.setOpemployeeid(1L);
            orderOperation.setOpemployeename("系统服务");
            orderOperation.setCreateTime(new Date());
            trainOrderOperationMapper.insertTrainOrderOperation(orderOperation);
        }
    }
}
